package com.hontech.desktoppastacooker.conn

import android.util.Log
import android.util.SparseArray
import com.hontech.desktoppastacooker.conn.frame.ResFrame
import kotlinx.coroutines.CompletableDeferred

class Router {

    private val contain = SparseArray< CompletableDeferred<ResFrame> >()

    fun set(seq: Int, cmd: Int): CompletableDeferred<ResFrame> {
        val promise = CompletableDeferred<ResFrame>()
        val index = (seq shl 8) + cmd
        synchronized(this) {
            contain.set(index, promise)
        }
        return promise
    }

    fun notify(frame: ResFrame) {
        var promise: CompletableDeferred<ResFrame>?
        val index = (frame.seq shl 8) + frame.cmd
        synchronized(this) {
            promise = contain.get(index)
            contain.delete(index)
        }
        if (promise == null) {
            Log.e("异常", "promise 没有 $frame")
            return
        }
        promise!!.complete(frame)
    }
}


